//
//  GameLayer.m
//  MusicGame
//
//  Created by Matthew on 8/19/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GameLayer.h"
#import "MenuLayer.h"
#import "ConveyorBelt.h"

#import "SimpleAudioEngine.h"
#import "CDAudioManager.h"
#import "CocosDenshion.h"

#import "Constants.h"

#define kGAMEOVERLOST NO
#define kGAMEOVERWON YES


@implementation GameLayer

@synthesize clockValue;
@synthesize level;

#pragma mark Class

+(CCScene *) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	GameLayer *layer = [GameLayer node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

#pragma mark init/dealloc

- (id)init
{
    if( self = [super init] ) {
        winSize = [[CCDirector sharedDirector] winSize];
        
        self.isTouchEnabled = YES;
        [self setLevel:0];
        
        [self setBackground:@"background1.png"];
        [self initLabels];
        
        [self setEnemy:@"monster1.png"];
        
        [self setFrames:@"frame2.png"];
        
//        //    x, y, radius
//        //    73,45,43; 
//        //    398,45,43;
//        //    48,123,43;
//        //    433,123,43;
//        //    48,206,43;
//        //    433,206,43;
//        //    73,282,43;
//        //    398,282,43;
//        arrFramesPosition = [NSMutableArray array];
//        
//        [arrFramesPosition addObject:[NSValue valueWithCGPoint:ccp(73, 45)]];
//        [arrFramesPosition addObject:[NSValue valueWithCGPoint:ccp(398, 45)]];
//
//        CGPoint p = [[arrFramesPosition objectAtIndex:0]CGPointValue];
//        CCLOG(@"x == %f", p.x);
//        //CCLOG(@"y == %@", p);        
        [self performSelectorInBackground:@selector(loadSoundFilesInBackground) withObject:nil];
        [self resetAndIncrementLevel];
    }
    
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

#pragma mark Set Up

- (void)initConveyorBeltLayerWithStartingMarkers:(int)markers beltSpeed:(float)beltSpeed beltInterval:(float)beltInterval
{
    conveyorBeltLayer = [[ConveyorBelt alloc] init];
    [conveyorBeltLayer setStartingMarkers:markers];
    [conveyorBeltLayer setBeltSpeed:beltSpeed];
    [conveyorBeltLayer setBeltInterval:beltInterval];
    [conveyorBeltLayer registerObserver:self];
    [self addChild:conveyorBeltLayer z:1];
}

- (void)initLabels
{
    clockLabel = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%04d", self.clockValue]
                                    fontName:@"Helvetica" fontSize:18];
    [clockLabel setColor:ccc3(0,192,0)];
    [clockLabel setPosition:ccp(25, 310)];
    [self addChild:clockLabel];
    
    levelLabel = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"Level %d", self.level]
                                    fontName:@"Helvetica" fontSize:18];
    [levelLabel setColor:ccc3(0,192,0)];
    [levelLabel setPosition:ccp(240, 310)];
    [self addChild:levelLabel];
    
    markerStatsLabel = [CCLabelTTF labelWithString:
                      [NSString stringWithFormat:NSLocalizedString(@"%d dead %d alive", @"Marker Stats"), 0, 0]
                                        fontName:@"Helvetica"
                                        fontSize:18];
    [markerStatsLabel setPosition:ccp( 240, 280 )];
    [markerStatsLabel setColor:ccc3(0,192,0)];
    [self addChild:markerStatsLabel];
}

/* render background */
-(void)setBackground:(NSString *)newBackground
{
    [self removeChild:background cleanup:YES];
    [background release];
    
    background = [CCSprite spriteWithFile:newBackground];
    [background setPosition:ccp(240, 160)];
    [self addChild:background z:0];
}

/* render enemy */
-(void)setEnemy:(NSString *)newEnemy;
{
    enemy = [CCSprite spriteWithFile:newEnemy];
    [enemy setPosition:ccp(winSize.width / 2, winSize.height / 2)];
    [self addChild:enemy z:10];
}

/* render 8 frames */
-(void)setFrames:(NSString *)newFrame;
{
    frame1 = [CCSprite spriteWithFile:newFrame];
    [frame1 setPosition:ccp(FRAME_1_X, FRAME_1_Y)];
    [self addChild:frame1 z:10];
    
    frame2 = [CCSprite spriteWithFile:newFrame];
    [frame2 setPosition:ccp(FRAME_2_X, FRAME_2_Y)];
    [self addChild:frame2 z:10];
    
    frame3 = [CCSprite spriteWithFile:newFrame];
    [frame3 setPosition:ccp(FRAME_3_X, FRAME_3_Y)];
    [self addChild:frame3 z:10];
    
    frame4 = [CCSprite spriteWithFile:newFrame];
    [frame4 setPosition:ccp(FRAME_4_X, FRAME_4_Y)];
    [self addChild:frame4 z:10];
    
    frame5 = [CCSprite spriteWithFile:newFrame];
    [frame5 setPosition:ccp(FRAME_5_X, FRAME_5_Y)];
    [self addChild:frame5 z:10];
    
    frame6 = [CCSprite spriteWithFile:newFrame];
    [frame6 setPosition:ccp(FRAME_6_X, FRAME_6_Y)];
    [self addChild:frame6 z:10];
    
    frame7 = [CCSprite spriteWithFile:newFrame];
    [frame7 setPosition:ccp(FRAME_7_X, FRAME_7_Y)];
    [self addChild:frame7 z:10];

    frame8 = [CCSprite spriteWithFile:newFrame];
    [frame8 setPosition:ccp(FRAME_8_X, FRAME_8_Y)];
    [self addChild:frame8 z:10];

    
//    frame1 = [CCSprite spriteWithFile:newFrame];
//    [frame1 setPosition:ccp(winSize.width / 4, (winSize.height * 3) / 4)];
//    [self addChild:frame1 z:10];
//    
//    frame2 = [CCSprite spriteWithFile:newFrame];
//    [frame2 setPosition:ccp(winSize.width / 8, winSize.height / 2)];
//    [self addChild:frame2 z:10];
//
//    frame3 = [CCSprite spriteWithFile:newFrame];
//    [frame3 setPosition:ccp(winSize.width / 4, winSize.height / 4)];
//    [self addChild:frame3 z:10];
//
//    frame4 = [CCSprite spriteWithFile:newFrame];
//    [frame4 setPosition:ccp((winSize.width * 3) / 4, (winSize.height * 3) / 4)];
//    [self addChild:frame4 z:10];
//
//    frame5 = [CCSprite spriteWithFile:newFrame];
//    [frame5 setPosition:ccp((winSize.width * 7) / 8, winSize.height / 2)];
//    [self addChild:frame5 z:10];
//
//    frame6 = [CCSprite spriteWithFile:newFrame];
//    [frame6 setPosition:ccp((winSize.width * 3) / 4, winSize.height / 4)];
//    [self addChild:frame6 z:10];

}

# pragma mark Reset

- (void)resetAndIncrementLevel
{
    int startMarkers = 1, timer = 05; float beltSpeed = 5, beltInterval = 1;
    //[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"ful_0163_cut_eqmaster.wav"];
    [[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"Love Paradise  - Nhac Khong Loi.mp3"];
    
    level++;
    
    if ( level == 2 ) {
        timer = 40;
        startMarkers = 40;
        beltSpeed = 4;
        beltInterval = 0.75;
    }
    else if( level == 3 ) {
        timer = 50;
        startMarkers = 80;
        beltSpeed = 3;
        beltInterval = 0.5;
    }
    else if( level != 1 ) {
        CCScene* menuScene = [MenuLayer scene];
        [[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:1 scene:menuScene]];
        return;
    }
    
    [self removeChildByTag:2 cleanup:true];
    [self resetLabels];
    [self initConveyorBeltLayerWithStartingMarkers:startMarkers beltSpeed:beltSpeed beltInterval:beltInterval];
    [self setClockValue:timer];
    
    [self schedule:@selector(tick:) interval:1];
    [conveyorBeltLayer start];
}


- (void)resetLabels
{
    [clockLabel setColor:ccc3(0,0,0)];
    [clockLabel setString:[NSString stringWithFormat:@"%04d", self.clockValue]];
    [levelLabel setString:[NSString stringWithFormat:@"Level %d", self.level]];
    [markerStatsLabel setString:[NSString stringWithFormat:NSLocalizedString(@"%d dead %d alive", @"Marker Stats"), 0, 0]];
}

-(void)removeConveyorBeltObject
{
    [self removeChild:conveyorBeltLayer cleanup:YES];
    [conveyorBeltLayer unregisterObserver:self];
    [conveyorBeltLayer release]; //also release its children
    conveyorBeltLayer = nil;
}

#pragma mark Game Play and Logic

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    return YES;
}

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self resetAndIncrementLevel];
}

- (void)tick:(ccTime)dt
{
    self.clockValue -= 1;
    [clockLabel setString:[NSString stringWithFormat:@"%04d", self.clockValue]];
    
    if (self.clockValue > 15) {
        [clockLabel setColor:ccc3(0, 0, 0)];
    }
    else if ( self.clockValue == 15 ) {
        [clockLabel setColor:ccc3(255, 140, 0)];
    }
    else if( self.clockValue == 10 ) {
        [clockLabel setColor:ccc3(255,0,0)];
    }
    else if ( self.clockValue <= 0 ) {
        [[SimpleAudioEngine sharedEngine] stopBackgroundMusic];
        [self gameOver:kGAMEOVERLOST];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath 
                      ofObject:(id)object change:(NSDictionary *)change 
                       context:(void *)context
{
    if( [keyPath isEqualToString:@"gameOver"] ) {
        [self gameOver:[object valueForKey:keyPath]];
    }
    else if( [keyPath isEqualToString:@"deadMarkers"] ) {
        [self updateMarkerStats:object withKeyPath:keyPath];
    }
}

-(void)gameOver:(NSNumber *)istatus
{
    bool status = [istatus boolValue];
    //CGSize winSize = [[CCDirector sharedDirector] winSize];
    
    // stop clock
    [self unschedule:@selector(tick:)];
    
    // stop conveyor belt; avoid multiple messages being sent
    [conveyorBeltLayer pause];
    
    // set level = -1 to prevent continued gameplay
    if( !status ) level = -1;
    
    // set up "Game Over" label + fade-in
    NSString *msg = status ? 
        NSLocalizedString(@"Game Over :) You Win!", @"Game Over - You Win Message") :
        NSLocalizedString(@"Game Over :( You Lose", @"Game Over - You Lost Message");
    [[SimpleAudioEngine sharedEngine] playEffect: status ? @"bell.wav" : @"buzz.wav" ];
    
    CCLabelTTF *label = [CCLabelTTF labelWithString:msg fontName:@"Futura-Medium" fontSize:20];
    [label setPosition:ccp( winSize.width / 2, winSize.height / 2)];
    [label setOpacity:0];
    [label setTag:2];
    [self addChild:label z:10];
    
    // fade in message; fade out markers, ultimately remove and release
    // conveyor belt and its children.
    [label runAction:[CCFadeIn actionWithDuration:1]];
    [conveyorBeltLayer runAction:[CCSequence actions:[CCFadeOut actionWithDuration:1], [CCCallFunc actionWithTarget:self selector:@selector(removeConveyorBeltObject)], nil]];
}

-(void)updateMarkerStats:(id)object withKeyPath:(NSString *)keyPath
{
    [markerStatsLabel setString:[NSString stringWithFormat: NSLocalizedString(@"%d dead %d alive", @"Marker Statistics Format String"),
                         [conveyorBeltLayer deadMarkers],
                          ([conveyorBeltLayer startingMarkers] - [conveyorBeltLayer deadMarkers])]];
}


#pragma mark Background

-(void)loadSoundFilesInBackground
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
     
    [[SimpleAudioEngine sharedEngine] preloadEffect:@"quack.wav"];
    [[SimpleAudioEngine sharedEngine] preloadEffect:@"bell.wav"];
    [[SimpleAudioEngine sharedEngine] preloadEffect:@"buzz.wav"];
    [[SimpleAudioEngine sharedEngine] preloadEffect:@"ful_0163_cut_eqmaster.wav"];
    
    [pool release];
}

@end
